<template>
	<view class="boxCav">
		<!-- <image class="bg" src="https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/1735285854000292.png" mode="widthFix"></image> -->
		<canvas
			canvas-id="hoCanvas"
			class="hoCanvas"
			v-if="canvasHeight"
			:style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
		></canvas>
		<cover-view class="saveBtn" v-if="showSave" @click="saveImg()">保存到相册</cover-view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			ID:0,
			canvasWidth: 375,
			canvasHeight: 0,

			logo: 'https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/1723617981177445.png',
			bgSrc: 'https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/1735282541800481.jpg',
			bgWidth: '',
			bgHeight: '',
			bgRatio: '',

			qrSrc: '',
			qrWidth: 188,
			qrHeight: 188,

			headSrc: '',
			headWidth: 76,
			headHeight: 76,

			userName: '用户昵称',

			qr: {},
			postUrl: '',
			Data: {},
			showSave: false,
			pa_info:null,
			canvasList:[],
		};
	},
	onLoad(e) {
		this.ID = e.id
	},
	created() {
		uni.showLoading({
			title: '海报正在生成...',
			icon: 'loading',
		});
		this.Data = this.$store.state.shopCanvas;
		// this.Data.ProductName = this.Data.ProductName.length > 12 ? this.Data.ProductName.slice(0, 12) + '...' : this.Data.ProductName
		// this.Data.ProductName = this.truncateText(this.Data.ProductName, 12, 2);
	},
	async mounted() {
		// await this.getUserInfo()
		// await this.CreateShareQR()
		await this.getHead();
		await this.getQR();
		this.paDetail()
	},

	methods: {
		async paDetail(){
		    let res =await this.$api.post('Place/Detail',{
		        ID:this.ID
		    })
		    if(res.code == 0){
		        this.pa_info = res.data
						this.canvasList = [res.data.HotValue.toString(),res.data.ZAN.toString(),res.data.PlaceData?.FansNum.toString()]
		        // this.paOrder[0].count = res.data.PlaceData?.ProductNum || 0
		        // this.paOrder[1].count = res.data.PlaceData?.TotalSaleQty || 0
		        // this.paOrder[2].count = res.data.PlaceData?.TotalSaleMoney || 0
		        // this.paOrder[3].count = res.data.HotValue
		        // this.paOrder[4].count = res.data.ZAN
		        // this.paOrder[5].count = res.data.PlaceData?.FansNum || 0
						this.drawFun();
		    }
		},
		goBack() {
			const pages = getCurrentPages();
			if (pages.length > 1) {
				// 如果页面栈长度大于1，则说明有上一页，可以返回
				uni.navigateBack();
			} else {
				// 如果没有上一页，则导航到首页
				uni.reLaunch({
						url: '/pages/tab/home'
				});
			}
		},
		truncateText(text, charsPerLine, maxLines) {
			// 分割成每行charsPerLine个字符
			const lines = text.match(new RegExp('.{1,' + charsPerLine + '}', 'g')) || [];

			// 只保留maxLines行
			const truncatedLines = lines.slice(0, maxLines);

			// 如果原始文本的行数超过了maxLines，最后添加省略号
			if (lines.length > maxLines) {
				truncatedLines[maxLines - 1] += '...';
			}

			// 将截取后的行连接成一个字符串
			return truncatedLines;
		},
		async getUserInfo() {
			let u = uni.getStorageSync('user');
			let res = await this.$api.post('User/GetUserInfo', {
				ID: u.UserID,
			});
			this.user = res.data;
		},
		async CreateShareQR() {
			let res = await this.$api.post('Action/CreateShareQR', {
				Page: 'pages/tab/home',
				scene: uni.getStorageSync('user').ID,
			});
			this.qr = res.data;
		},
		getHead() {
			return new Promise((resolve, reject) => {
				this.headSrc = this.Data.HeadImgUrl;
				this.headSrc = 'https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/17329525852691481.png'
				resolve(this.headSrc);
			});
		},
		getQR() {
			return new Promise((resolve, reject) => {
				setTimeout(() => {
					this.qrSrc = 'https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/1735283296056112.png' || this.Data.Qr;
					// this.qrSrc = 'https://giftapp.oss-cn-shenzhen.aliyuncs.com/upload/1724925186646988.png'
					resolve(this.qrSrc);
				}, 1000);
			});
		},

		//绘制头像
		headDraw(ctx, src, headW, headH) {
			let top = 65;
			let left = 42;
			let width = 20;
			let height = 20;

			const R = width / 2;
			const centerX = left + R;
			const centerY = top + R;
			//头像中心坐标
			const headX = headW / 2;
			const headY = headH / 2;
			let sx = 0,
				sy = 0,
				sWidth = headW,
				sHeight = headH;
			//横图
			if (headW > headH) {
				sWidth = headH;
				sy = 0;
				sx = headX - sWidth / 2;
			} else {
				sHeight = headW;
				sx = 0;
				sy = headY - sHeight / 2;
			}

			// let avaImg_w,avaImg_h
			// let rat = headW / headH
			// let rCri = 55	//头像直径
			// if (headW <= headH) {
			// 	avaImg_w = rCri
			// 	avaImg_h = rCri/rat
			// }else{
			// 	avaImg_h = rCri
			// 	avaImg_w = rCri*rat
			// }
			
			//馆名
			ctx.font = '16px PingFang-SC';
			ctx.setFillStyle('#111');
			ctx.fillText(this.pa_info.PlaceName, left+25, top + 16);
			

			ctx.save(); // 保存当前的绘图上下文
			// ctx.arc(centerX, centerY, R, 0, Math.PI * 2);
			// ctx.clip();
			ctx.drawImage(src, sx, sy, sWidth, sHeight, left, top, width, height);
			ctx.restore();
		},
		shopImgDraw(ctx, src, headW, headH) {
			const radius = 12; // 圆角半径
			const width = 290; // 目标宽度
			const height = 290; // 目标高度
			let top = 101;
			let left = 42;

			const R = width / 2;
			const centerX = left + R;
			const centerY = top + R;
			//头像中心坐标
			const headX = headW / 2;
			const headY = headH / 2;
			let sx = 0,
				sy = 0,
				sWidth = headW,
				sHeight = headH;
			//横图
			if (headW > headH) {
				sWidth = headH;
				sy = 0;
				sx = headX - sWidth / 2;
			} else {
				sHeight = headW;
				sx = 0;
				sy = headY - sHeight / 2;
			}

			// 开始绘制路径
			ctx.beginPath();
			ctx.moveTo(left + radius, top);
			ctx.lineTo(left + width - radius, top);
			ctx.arcTo(left + width, top, left + width, top + radius, radius);
			ctx.lineTo(left + width, top + height - radius);
			ctx.arcTo(left + width, top + height, left + width - radius, top + height, radius);
			ctx.lineTo(left + radius, top + height);
			ctx.arcTo(left, top + height, left, top + height - radius, radius);
			ctx.lineTo(left, top + radius);
			ctx.arcTo(left, top, left + radius, top, radius);
			ctx.closePath();

			ctx.clip();

			ctx.drawImage(src, sx, sy, sWidth, sHeight, left, top, width, height);
			// ctx.restore();
		},
		//二维码部分
		QrDraw(ctx, qr) {
			// ctx.textAlign = 'center'
			let x = 58
			let textPadding = this.canvasWidth*0.0726
			let textWidth = (this.canvasWidth - textPadding*2) / 3
			
			let drawWidth = (textWidth+textPadding)/2
			
			
			// ctx.textAlign = 'center'
			// ctx.fillText('1000', drawWidth, 430);
			// ctx.fillText('3721',drawWidth+100, 430,textWidth);
			// ctx.fillText('4759',drawWidth+200, 430,textWidth);
			
			const availableWidth = this.canvasWidth - textPadding * 2 - 8; // 减去内边距后的可用宽度
			const sectionWidth = availableWidth / 3; // 每一份的宽度
		
			const titleList = ['人气热度','点赞人数','粉丝人数']
			ctx.font='500 12px PingFang-SC'
			ctx.setFillStyle('#111');
			for (let i = 0; i < 3; i++) {
				const text1 = titleList[i];
				const x = textPadding+2 + i * sectionWidth; // 计算每一份的起始x坐标
				const textWidth = ctx.measureText(text1).width; // 获取文字的宽度
				const textX = x + (sectionWidth - textWidth) / 2; // 计算文字居中的x坐标
				// 绘制文字
				ctx.fillText(text1, textX, 450); // y轴位置可以根据需要调整
			}
			
			// const countList = ['1000','109','23']
			
			// ctx.textAlign = 'center'
			ctx.font='bold 24px PingFang-SC'
			ctx.setFillStyle('#5d8bf8');
			for (let i = 0; i < 3; i++) {
				const text1 = this.canvasList[i];
				const x = textPadding+2 + i * sectionWidth; // 计算每一份的起始x坐标
				const textWidth = ctx.measureText(text1).width; // 获取文字的宽度
				const textX = x + (sectionWidth - textWidth) / 2; // 计算文字居中的x坐标
				// 绘制文字
				ctx.fillText(text1, textX, 430); // y轴位置可以根据需要调整
			}
			
			
			// ctx.fillText('人气热度', drawWidth, 450,100);
			// ctx.fillText('点赞人数', drawWidth+100, 450,100);
			// ctx.fillText('粉丝人数', drawWidth+200, 450,100);
			
			//二维码
			ctx.drawImage(qr, 263, 481, 66, 66);
		},

		drawFun() {
			const that = this;
			//背景
			let promiseBg = new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: that.bgSrc,
					success: (res) => {
						that.bgWidth = res.width;
						that.bgHeight = res.height;
						that.bgRatio = res.width / res.height;
						resolve(res);
					},
					fail: (err) => {
						console.log('promiseBg错误');
						this.$pv.msg('[Error]CreateBackground is Error');
						reject(err);
					},
				});
			});
			//二维码
			let promiseQR = new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: that.qrSrc,
					success: (res) => {
						resolve(res);
					},
					fail: (err) => {
						console.log('promiseQR错误');
						this.$pv.msg('[Error]CreateShareQR is Error');
						reject(err);
					},
				});
			});

			let promiseShopImg = new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: that.pa_info.Banner,
					success: (res) => {
						resolve(res);
					},
					fail: (err) => {
						console.log('promiseQR错误');
						this.$pv.msg('[Error]CreateShareQR is Error');
						reject(err);
					},
				});
			});
			//头像
			let promiseHead = new Promise((resolve, reject) => {
				uni.getImageInfo({
					src: that.headSrc,
					success: (res) => {
						resolve(res);
					},
					fail: (err) => {
						console.log('promiseHead错误');
						this.$pv.msg('[Error]HeadImgUrl is Error');
						reject(err);
					},
				});
			});

			setTimeout(() => {
				const query = uni.createSelectorQuery();
				//指定要获取的属性，这里设置为size: true表示要获取尺寸信息。
				query
					.select('.hoCanvas')
					.fields({ node: true, size: true }, (res) => {
						that.canvasWidth = 375;
						that.canvasHeight = that.canvasWidth / that.bgRatio;
						console.log(that.canvasHeight,'11111');
						
						Promise.all([promiseBg, promiseQR, promiseHead, promiseShopImg])
							.then((rex) => {
								console.log('----------', rex);

								const ctx = uni.createCanvasContext('hoCanvas', this);
								// ctx.canvasWidth = this.canvasWidth; // 背景图片的实际宽度
								// ctx.canvasHeight = this.canvasHeight ;
								//绘制背景
								ctx.drawImage(rex[0].path, 0, 0, that.canvasWidth, that.canvasHeight);

								//绘制头像
								that.headDraw(ctx, rex[2].path, rex[2].width, rex[2].height);

								this.QrDraw(ctx, rex[1].path);
								that.shopImgDraw(ctx, rex[3].path, rex[3].width, rex[3].height);

								ctx.draw();

								setTimeout(() => {
									uni.canvasToTempFilePath(
										{
											x: 0,
											y: 0,
											width: that.canvasWidth,
											height: that.canvasHeight,
											destWidth: that.canvasWidth * 2,
											destHeight: that.canvasHeight * 2,
											canvasId: 'hoCanvas',
											success: function (res) {
												that.postUrl = res.tempFilePath;
												// that.saveImg();
												that.showSave = true;
												// that.$emit('showSaveFun',true)
												if (that.postUrl) {
													uni.hideLoading();
													// that.$emit('getCanvasImg',res.tempFilePath)
												}
											},
											fail: function (err) {
												console.log(err);
											},
										},
										this
									);
								}, 500);
							})
							.catch((err) => {
								console.log('========errrr',err);
								uni.hideLoading();
								uni.showModal({
									title: '异常错误',
									content: '图片生成失败!!!\n[QRError:Damaged QR code]',
									showCancel: false,
									success: (res) => {
										if (res.confirm) uni.navigateBack();
									},
								});
							});
					})
					.exec();
			}, 1000);
		},
		saveImg() {
			const that = this;
			//将图片保存到相册
			uni.saveImageToPhotosAlbum({
				filePath: that.postUrl,
				success(res) {
					uni.showModal({
						title: '保存成功',
						content: '图片成功保存到相册了，快去分享朋友圈吧',
						showCancel: false,
						confirmText: '好的',
						success: function (res) {
							if (res.confirm) {
							}
							// that.hideShareImg()
						},
					});
				},
				fail(err) {
					console.log(err);
				},
			});
			console.log('保存');
		},
	},
};
</script>

<style lang="scss">
page {
	background: linear-gradient(141deg, #f7bb84 0%, #f53f27 100%);
}

.bg{
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	
}
.boxCav {
	padding-bottom: 150rpx;
	
}
.hoCanvas {
	width: 350px;
	height: 650px;
	border-radius: 8rpx;
	overflow: hidden;
	margin: 20rpx auto;
	z-index: 1;
}
.saveBtn {
	position: fixed;
	bottom: 10rpx;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 90%;
	height: 96rpx;
	text-align: center;
	line-height: 96rpx;
	background: #ffffff;
	border-radius: 8px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: bold;
	font-size: 16px;
	color: #5d8bf8;
	z-index: 999999;
}
</style>
